package httpclient_test_1;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用HttpClient接收请求
 * 1.创建HttpClient对象
 * 2.创建请求方法的实例,并传入指定的url,get方法创建Get实例.post方法创建Post实例
 * 3.如果需要设置请求参数可调用HttpGet和HttpPost共同的方法setParams(params)的方法来设置请求参数,对于Post请求
 * 而言也可以通过HttpPost实例的setEntity(entity)设置请求参数
 * 4.调用HttpClient对象的execute(HttpRequest)发送请求,最后返回一个Response
 * 5.调用HttpResponse的getAllHeaders(),getHeaders(name)获取服务器响应头,调用HttpResponse的getEntity()方法
 * 可获取HttpEntity对象,该对象包装了服务器的响应内容.程序可以通过该对象获取服务器的响应内容
 * 6.释放连接,无论成功与否都要释放连接
 *
 */
public class HttpClientTest_1 {
    public static void main(String[] args) throws IOException {
        List<NameValuePair> formsParams = new ArrayList<NameValuePair>();
        formsParams.add(new BasicNameValuePair("account",""));
        formsParams.add(new BasicNameValuePair("password",""));
        HttpEntity httpEntity = new UrlEncodedFormEntity(formsParams,"utf-8");
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(5000).setSocketTimeout(5000)
                .setConnectionRequestTimeout(5000).build();
        //创建HttpClient对象
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost("http://cnivi.com.cn/login");
        post.setEntity(httpEntity);
        post.setConfig(config);
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200){
            HttpEntity entity = response.getEntity();
            String message = EntityUtils.toString(entity,"utf-8");
            System.out.println(message);
        }else{
            System.out.println("请求失败");
        }

    }
}
